package gui;

import static com.googlecode.charts4j.Color.GREEN;
import static com.googlecode.charts4j.Color.*;
import static com.googlecode.charts4j.Color.RED;
import static com.googlecode.charts4j.Color.SKYBLUE;
import static com.googlecode.charts4j.Color.WHITE;
import jade.core.AID;
import jade.core.Agent;
import jade.tools.gui.AIDAddressList;
import jade.util.leap.HashMap;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JComboBox;
import java.awt.BorderLayout;
import javax.swing.JLabel;
import javax.swing.JCheckBox;

import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Component;
import java.awt.Insets;
import java.awt.LayoutManager;
import java.awt.Panel;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;

import statics.TradingConst;

import com.googlecode.charts4j.AxisLabels;
import com.googlecode.charts4j.AxisLabelsFactory;
import com.googlecode.charts4j.AxisStyle;
import com.googlecode.charts4j.AxisTextAlignment;
import com.googlecode.charts4j.BarChart;
import com.googlecode.charts4j.BarChartPlot;
import com.googlecode.charts4j.Color;
import com.googlecode.charts4j.Data;
import com.googlecode.charts4j.DataUtil;
import com.googlecode.charts4j.Fills;
import com.googlecode.charts4j.GCharts;
import com.googlecode.charts4j.Line;
import com.googlecode.charts4j.LineChart;
import com.googlecode.charts4j.LineStyle;
import com.googlecode.charts4j.LinearGradientFill;
import com.googlecode.charts4j.Plot;
import com.googlecode.charts4j.Plots;
import com.googlecode.charts4j.Shape;
import com.googlecode.charts4j.collect.ImmutableList;

import agents.HomeAgent;

public class HomeGUI extends JFrame implements ActionListener, FocusListener {
	
	private static final int MAX_WIDTH = 500;

	private static final int MAX_HEIGHT = 450;

	private static final int AVERAGE_SPENDING_SCALES = 3;

	private static final int CHART_WIDTH = 400;

	private static final int CHART_HEIGHT = 250;

	private static double SCALE_MULTIPLIER;
	
	protected int NUM_POINTS = (int)Math.ceil((double)TradingConst.HOURS_IN_DAY/((double)TradingConst.HOME_AGENT_MIN_TO_UPDATE_LOAD/TradingConst.MIN_IN_HOUR));
	
	protected HomeAgent myHomeAgent;
	
	public Hashtable<String, Double> applianceList;
	protected ArrayList<ApplianceCheckBox> appliancePaneList = new ArrayList<ApplianceCheckBox>();
	JPanel ApplianceAddPanel;
    JTextField tfAppName;
    JLabel lbAppName;
    JTextField tfAppPower;
    JLabel lblAppPower;
    JButton btnAppAdd;
    JPanel pnlAppliances;
    JCheckBox AirCon;
    JPanel pnlGraph;
    JPanel pnlCurrentUsage;
    JLabel lblUsagePower;
    JLabel lblUsagePrice;
    JLabel lblUsageDollarAmount;
    private JPanel appliancePane = new JPanel();
    private JPanel mainPane = new JPanel();
	private JTextField tfMonthlyBudget;

	private JLabel lblMonthlyBudget;

	private JButton btnSetMonthlyBudget;

	private double dMonthlyBudgetDollars;

	private JLabel lblHouseholdUsageImage;

	private LineChart chart;

	private double[] TargetConsumptionDollars;

	private ArrayList<Double> CurrentConsumptionDollars;

	private JLabel lbAddButton;

	private double mAmountSpentThisPeriodMonthlyNormalized;

	private JLabel lblGraphImageBuff;

	private JButton btnToogleUsagePane;

	private JButton btnToggleAppPane;

	private JPanel controlPane;

	private JLabel lblApplianceUsageImage;
	
	private TreeMap<String, Double> appliancePowerUsage = new TreeMap<String, Double>(); 
	private TreeMap<String, Double> applianceWattage = new TreeMap<String, Double>();

	private boolean bAccessingApplianceUsage;

	private TreeMap<String, Boolean> applianceOn = new TreeMap<String, Boolean>();

	private JPanel pnlBudget;

	private JPanel pnlBudgetAndCurrentUsage;

	private JLabel lblUsageWarning;

	private JLabel lblRetailerName;
	
	public HomeGUI(HomeAgent a) {
		super(a.getAID().getName());
		myHomeAgent = a;
		applianceList = new Hashtable<String, Double>();
		//applianceList.put("Washer", 800.0);
		//applianceList.put("AirCon", 1000.0);
		
		//SCALE_MULTIPLIER = 100;
		InitUIComponents();
		InitChart();
		InitSomeAppliances();
		bAccessingApplianceUsage= false;
		UpdateChart(0, 0.0, myHomeAgent.getIdealAverageSpendingPerPeriod());
    }
	private void InitSomeAppliances() {
		try
		{
			AddAppliance("Fridge", 500);
			AddAppliance("Lights", 300);
			AddAppliance("Solar Panel", -200);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally
		{
		}
	}
	private void InitUIComponents() {
		//testLayout customLayout = new testLayout();
		setBounds(0,0,MAX_WIDTH, MAX_HEIGHT);
		
		appliancePane.setLayout(new BorderLayout());
        //getContentPane().setFont(new Font("Helvetica", Font.PLAIN, 12));
        //getContentPane().setLayout(customLayout);
		
        ApplianceAddPanel = new JPanel();
        ApplianceAddPanel.setLayout(new GridLayout(0,2));
        
        lbAppName = new JLabel("Appliance Name");
        ApplianceAddPanel.add(lbAppName);
        tfAppName = new JTextField("App Name",10);
        tfAppName.addFocusListener(this);
        ApplianceAddPanel.add(tfAppName);
        lblAppPower = new JLabel("Appliance Power ");
        ApplianceAddPanel.add(lblAppPower);
        tfAppPower = new JTextField("Power",10);
        tfAppPower.addFocusListener(this);
        ApplianceAddPanel.add(tfAppPower);
        lbAddButton = new JLabel("Click here");
        ApplianceAddPanel.add(lbAddButton);
        btnAppAdd = new JButton("Add Appliance");
        ApplianceAddPanel.add(btnAppAdd);
        btnAppAdd.addActionListener(this);
        
        appliancePane.add(ApplianceAddPanel, BorderLayout.NORTH);
        
        pnlAppliances = new JPanel();
        pnlAppliances.setLayout(new GridLayout(0, 2));
        appliancePane.add(pnlAppliances,BorderLayout.WEST);

        appliancePane.setVisible(false);
        
        //Current usage
        pnlCurrentUsage = new JPanel();
        pnlCurrentUsage.setLayout(new FlowLayout());

        lblUsagePower = new JLabel("Current Power");
        pnlCurrentUsage.add(lblUsagePower);

        lblUsagePrice = new JLabel("Current Price");
        pnlCurrentUsage.add(lblUsagePrice);

        lblUsageDollarAmount = new JLabel("Cost (normalised)");
        lblUsageDollarAmount.setOpaque(true);
        pnlCurrentUsage.add(lblUsageDollarAmount);
        
        //Budget Usage
        lblMonthlyBudget = new JLabel("Monthly budget");
        tfMonthlyBudget = new JTextField("100.00");
        tfMonthlyBudget.addFocusListener(this);
        btnSetMonthlyBudget = new JButton("Set");
        btnSetMonthlyBudget.addActionListener(this);
        pnlBudget = new JPanel();
        pnlBudget.setLayout(new FlowLayout());
        pnlBudget.add(lblMonthlyBudget);
        pnlBudget.add(tfMonthlyBudget);
        pnlBudget.add(btnSetMonthlyBudget);
        lblUsageWarning = new JLabel();
        pnlBudgetAndCurrentUsage = new JPanel();
        pnlBudgetAndCurrentUsage.setLayout(new GridLayout(0,1));
        pnlBudgetAndCurrentUsage.add(pnlBudget);
        lblRetailerName = new JLabel();
        //pnlBudgetAndCurrentUsage.add(lblRetailerName);
        pnlBudgetAndCurrentUsage.add(pnlCurrentUsage);
		lblUsageWarning.setText("Warning! Exceeding budget!!!");
		lblUsageWarning.setOpaque(true);
		lblUsageWarning.setBackground(java.awt.Color.RED);
		lblUsageWarning.setVisible(false);
        pnlBudgetAndCurrentUsage.add(lblUsageWarning);

        //Graph
        pnlGraph = new JPanel();
        lblHouseholdUsageImage = new JLabel();
        lblHouseholdUsageImage.setVisible(true);
        lblApplianceUsageImage = new JLabel();
        lblApplianceUsageImage.setVisible(false);
        //Control
        btnToggleAppPane = new JButton("Toggle App Pane");
        btnToggleAppPane.addActionListener(this);
       
        btnToogleUsagePane = new JButton("Trend/Usage Graph");
        btnToogleUsagePane.addActionListener(this);
        
        controlPane = new JPanel();
        controlPane.setLayout(new FlowLayout());
        controlPane.add(btnToggleAppPane);
        controlPane.add(btnToogleUsagePane);
        
        Container con = this.getContentPane();
        mainPane.setBounds(new Rectangle(MAX_WIDTH,MAX_HEIGHT));
        mainPane.add(controlPane,BorderLayout.PAGE_START);
        mainPane.add(appliancePane,BorderLayout.LINE_START);
        mainPane.add(pnlGraph,BorderLayout.LINE_END);
        mainPane.add(pnlBudgetAndCurrentUsage,BorderLayout.PAGE_END);
       
		con.add(mainPane);
        validate();
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
	}
	
	@Override
	public void actionPerformed(ActionEvent arg0) {
		Object source = arg0.getSource();
		if(source == btnAppAdd)
		{
			try{
				AddAppliance(tfAppName.getText(),Double.parseDouble(tfAppPower.getText()));
			}catch (Exception exc)
			{
				JOptionPane.showMessageDialog(this, "Cannot add Appliance. Error:" + exc.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
			}
		}
		if(source == btnSetMonthlyBudget)
		{
			try{
				dMonthlyBudgetDollars = Double.parseDouble(tfMonthlyBudget.getText());
				myHomeAgent.SetMonthlyBudget(dMonthlyBudgetDollars);
				UpdateMonthyBudgetGraphData(dMonthlyBudgetDollars);
			}catch (Exception exc)
			{
				JOptionPane.showMessageDialog(this, "Cannot update budget. Error:" + exc.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
			}
		}
		if(source == btnToggleAppPane)
		{
			appliancePane.setVisible(!appliancePane.isVisible());
		}
		
		if(source == btnToogleUsagePane)
		{
			lblHouseholdUsageImage.setVisible(!lblHouseholdUsageImage.isVisible());
			lblApplianceUsageImage.setVisible(!lblApplianceUsageImage.isVisible());
		}
	}
	private void UpdateMonthyBudgetGraphData(double dMonthlyBudgetDollars) {
		SCALE_MULTIPLIER = (1.0/AVERAGE_SPENDING_SCALES);
    	TargetConsumptionDollars = new double[NUM_POINTS];
    	 for (int i = 0; i < NUM_POINTS; i++) {
             TargetConsumptionDollars[i] = dMonthlyBudgetDollars*SCALE_MULTIPLIER;
         }
	}
	private void AddAppliance(String appName, double appPower) throws Exception {
		while(bAccessingApplianceUsage)
		{
		}
		//TODO: check to make sure appName not exist
		if(applianceList.containsKey(appName))
		{
			throw new Exception("Appliance already exist");
		}
		applianceList.put(appName, appPower);
		ApplianceCheckBox appCB = new ApplianceCheckBox(appName,appPower);
		appCB.setSelected(true);
		pnlAppliances.add(appCB);
		appCB.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent arg0) {
				ApplianceCheckBox source = (ApplianceCheckBox)arg0.getSource();
				myHomeAgent.ChangeApplianceState(source.AppName, source.isSelected());
				applianceOn.remove(source.AppName);
				applianceOn.put(source.AppName,source.isSelected());
			}
		});
		appliancePowerUsage.put(appName, 0.0);
		applianceWattage.put(appName, appPower);
		applianceOn.put(appName,true);
		appliancePaneList.add(appCB);
		this.validate();
		//this.pack();
		myHomeAgent.AddAppliance(appName, appPower, true);
	}
	@Override
	public void focusGained(FocusEvent arg0) {
		JTextField source = (JTextField)arg0.getSource();
		if(source == tfAppPower)
		{
			source.setText("");
		}
	}
	@Override
	public void focusLost(FocusEvent arg0) {
		// Nothing
	}
	public void UpdateFromHomeAgent(int currentTickCount, Double powerRequired,
			double rateInDollarPerKWh, double amountSpentThisPeriod,
			double idealAverageSpendingPerPeriod, boolean isExceeding, String purchasedRetailer) {
		
		// Update UI
		DecimalFormat df = new DecimalFormat("#.####");
		lblUsagePower.setText(purchasedRetailer + " - Required " + df.format(powerRequired*TradingConst.WATT_TO_KW)+ "KW");
		lblUsagePrice.setText(" - Price $" + df.format(rateInDollarPerKWh) + "/KWh");
		
		mAmountSpentThisPeriodMonthlyNormalized = amountSpentThisPeriod*
		TradingConst.NormaliseMinToMonth(TradingConst.HOME_AGENT_MIN_TO_UPDATE_LOAD);
		
		lblRetailerName.setText("Retailer: " + purchasedRetailer);
		
		//Multiply by -1 shows debit/credit value
		lblUsageDollarAmount.setText(" = (Monthly) $" + df.format((-1)*mAmountSpentThisPeriodMonthlyNormalized));
		double normalisedIdealSpendingThisPeriod = idealAverageSpendingPerPeriod*TradingConst.NormaliseMinToMonth(TradingConst.HOME_AGENT_MIN_TO_UPDATE_LOAD);
		if(mAmountSpentThisPeriodMonthlyNormalized > normalisedIdealSpendingThisPeriod)
		{
			lblUsageDollarAmount.setBackground(java.awt.Color.RED);
			lblUsageWarning.setText("Warning! Exceeding Budget");
			lblUsageWarning.setVisible(true);
		}else
		{
			lblUsageDollarAmount.setBackground(java.awt.Color.GREEN);
			lblUsageWarning.setVisible(false);
		}
		if((int)mAmountSpentThisPeriodMonthlyNormalized ==0
			&& powerRequired != 0)
		{
			if(powerRequired > 0)
			{
				//buying - no power
				lblUsageWarning.setText("Warning! Unable to buy power! A blackout may have occurred");
			}else if(powerRequired < 0)
			{
				lblUsageWarning.setText("Warning! Unable to sell power! Grid may have been overloaded");
			}
			lblUsageWarning.setVisible(true);	
		}
		//updating usage
		
		bAccessingApplianceUsage = true;
		Map.Entry<String,Double> entry;
		Iterator<Map.Entry<String,Double>>  it = appliancePowerUsage.entrySet().iterator();

		while(it.hasNext())
		{
			entry = it.next();
			if(applianceOn.get(entry.getKey()))
			{
				Double currentPowerUsage = entry.getValue();
				currentPowerUsage += applianceWattage.get(entry.getKey())*rateInDollarPerKWh*TradingConst.WATT_TO_KW
								*TradingConst.HOME_AGENT_MIN_TO_UPDATE_LOAD/TradingConst.MIN_IN_HOUR;
				entry.setValue(currentPowerUsage);
			}
		}
		bAccessingApplianceUsage = false;
		UpdateChart(currentTickCount,mAmountSpentThisPeriodMonthlyNormalized, normalisedIdealSpendingThisPeriod);
		UpdateApplianceChart();
		
	}
	/**
     * Display the chart in a swing window.
     *
     *
     * @param urlString
     *            the url string to display.
     * @throws IOException
     */
    private void displayUrlString(final String urlString, JLabel holder) throws IOException{
    	lblGraphImageBuff = new JLabel(new ImageIcon(ImageIO.read(new URL(urlString))));
    	lblGraphImageBuff.setVisible(holder.isVisible());
    	//this.getContentPane().remove(lblGraphImage);
    	pnlGraph.removeAll();
    	holder = lblGraphImageBuff;
        //this.getContentPane().add(lblGraphImage,BorderLayout.EAST);
    	pnlGraph.add(holder,BorderLayout.EAST);
    	pnlGraph.validate();
        validate();
        //this.pack();
        //this.setVisible(true);
    }
    protected void InitChart()
    {
    	SCALE_MULTIPLIER = (1.0/AVERAGE_SPENDING_SCALES);
    	CurrentConsumptionDollars = new ArrayList<Double>(NUM_POINTS);
    	TargetConsumptionDollars = new double[NUM_POINTS];
    	double targetSpending = myHomeAgent.getIdealAverageSpendingPerPeriod()*TradingConst.NormaliseMinToMonth(TradingConst.HOME_AGENT_MIN_TO_UPDATE_LOAD);
    	 for (int i = 0; i < NUM_POINTS; i++) {
             TargetConsumptionDollars[i] = targetSpending*SCALE_MULTIPLIER;
             CurrentConsumptionDollars.add(targetSpending*SCALE_MULTIPLIER);
         }
    }
    
    public static double[] toPrimitive(Double[] array) {
    	  if (array == null) {
    		  return null;
    	  } else if (array.length == 0) {
    		  return new double[0];
    	  }
    	  final double[] result = new double[array.length];
    	  for (int i = 0; i < array.length; i++) {
    	    result[i] = array[i].doubleValue();
    	  }
    	  return result;
    	}
    
    protected void UpdateApplianceChart()
    {
    	bAccessingApplianceUsage = true;
    	double dMax_usage = 0.0;
    	for(Double value:appliancePowerUsage.values())
    	{
    		if (value > dMax_usage )
    		{
    			dMax_usage = value;
    		}
    	}
    	
        if(dMax_usage < 0.2)
        	dMax_usage = 0.2;
        Data applianceData= DataUtil.scaleWithinRange(0, dMax_usage,(toPrimitive((appliancePowerUsage.values()).toArray(new Double[0]))));
        
        BarChartPlot usagePlot = Plots.newBarChartPlot(applianceData, GREEN, "Usage by appliance");
        BarChart chart = GCharts.newBarChart(usagePlot);

        // Defining axis info and styles
        AxisStyle axisStyle = AxisStyle.newAxisStyle(BLACK, 13, AxisTextAlignment.CENTER);
        AxisLabels applianceLbl = AxisLabelsFactory.newAxisLabels("Appliances", 50.0);
        applianceLbl.setAxisStyle(axisStyle);
        AxisLabels applianceListLbl = AxisLabelsFactory.newAxisLabels(appliancePowerUsage.keySet().toArray(new String[0]));
        applianceListLbl.setAxisStyle(axisStyle);
        AxisLabels usageLbl = AxisLabelsFactory.newAxisLabels("KWh", 50.0);
        usageLbl.setAxisStyle(axisStyle);
        AxisLabels usagePower = AxisLabelsFactory.newNumericRangeAxisLabels(0, dMax_usage);
        usagePower.setAxisStyle(axisStyle);

        bAccessingApplianceUsage = false;
        // Adding axis info to chart.
        chart.addYAxisLabels(usagePower);
        chart.addYAxisLabels(usageLbl);
        chart.addXAxisLabels(applianceListLbl);
        chart.addXAxisLabels(applianceLbl);
        //chart.addTopAxisLabels(usagePower);
        chart.setHorizontal(false);
        chart.setSize(CHART_WIDTH, CHART_HEIGHT);
        if(applianceList.size() > 0)
        {
        	chart.setSpaceBetweenGroupsOfBars((int)(CHART_WIDTH*.6)/(applianceList.size()+1));
        }
        chart.setTitle("Usage by appliances", BLACK, 16);
        ///51 is the max number of medals.
        chart.setGrid((50.0/dMax_usage)*20, 600, 3, 2);
        chart.setBackgroundFill(Fills.newSolidFill(LIGHTGREY));
        LinearGradientFill fill = Fills.newLinearGradientFill(0, Color.newColor("E37600"), 100);
        fill.addColorAndOffset(Color.newColor("DC4800"), 0);
        chart.setAreaFill(fill);
        String url = chart.toURLString();
        JLabel holder = lblApplianceUsageImage;
        if(holder.isVisible())
        {
	        try {
				displayUrlString(url,holder);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				/*JOptionPane.showMessageDialog(this, 
											"Problem updating graph",
											"Error",
											JOptionPane.ERROR_MESSAGE);*/
				e.printStackTrace();
			}
        }
    }
    protected void UpdateChart(int currentTickCount, double amountSpentThisPeriodMonthlyNormalized, double idealAverageSpendingPerPeriodMonthlyNormalized)
    {
    	CurrentConsumptionDollars.add(amountSpentThisPeriodMonthlyNormalized*SCALE_MULTIPLIER);
    	if(CurrentConsumptionDollars.size() > NUM_POINTS)
    	{
    		//too many, remove
    		CurrentConsumptionDollars.remove(0);
    	}
    	Double[] temp = new Double[NUM_POINTS];
        CurrentConsumptionDollars.toArray(temp);
        
        Line lineTargetConsumption = Plots.newLine(Data.newData(TargetConsumptionDollars), Color.newColor("CA3D05"), "Target Usage");
        lineTargetConsumption.setLineStyle(LineStyle.newLineStyle(3, 1, 0));
        lineTargetConsumption.addShapeMarkers(Shape.DIAMOND, Color.newColor("CA3D05"), 12);
        lineTargetConsumption.addShapeMarkers(Shape.DIAMOND, Color.WHITE, 8);
        
        Line line2 = Plots.newLine(Data.newData(toPrimitive(temp)), SKYBLUE, "Current Usage");
        line2.setLineStyle(LineStyle.newLineStyle(3, 1, 0));
        line2.addShapeMarkers(Shape.DIAMOND, SKYBLUE, 12);
        line2.addShapeMarkers(Shape.DIAMOND, Color.WHITE, 8);
        
        //ImmutableList<Plot> lines = new ImmutableList<Plot>();
        //lines.add(line1);
        //lines.add(line2);
        // Defining chart.
        chart = GCharts.newLineChart(lineTargetConsumption, line2);
        //chart = new LineChart(lines);
        chart.setSize(CHART_WIDTH, CHART_HEIGHT);
        chart.setTitle("Energy usage and target in dollars", WHITE, 14);
        //chart.addHorizontalRangeMarker(40, 60, Color.newColor(RED, 30));
        //chart.addVerticalRangeMarker(70, 90, Color.newColor(GREEN, 30));
        chart.setGrid(0.01, 0.01, 3, 2);

        // Defining axis info and styles
        AxisStyle axisStyle = AxisStyle.newAxisStyle(WHITE, 12, AxisTextAlignment.CENTER);
        
        AxisLabels xAxisExplainLabel = AxisLabelsFactory.newAxisLabels("Hours (24 hours windows)", 50.0);
        xAxisExplainLabel.setAxisStyle(AxisStyle.newAxisStyle(WHITE, 14, AxisTextAlignment.CENTER));
        AxisLabels xAxisNumericLabel = AxisLabelsFactory.newNumericRangeAxisLabels(0.0, TradingConst.HOURS_IN_DAY, (int)10*(TradingConst.HOME_AGENT_MIN_TO_UPDATE_LOAD/TradingConst.MIN_IN_HOUR));
        xAxisNumericLabel.setAxisStyle(axisStyle);
        
        AxisLabels yAxisExplainLabel = AxisLabelsFactory.newAxisLabels("$/m", 50.0);
        yAxisExplainLabel.setAxisStyle(axisStyle);
        AxisLabels yAxisNumericLabel = AxisLabelsFactory.newNumericRangeAxisLabels(0.0, 
        		AVERAGE_SPENDING_SCALES*idealAverageSpendingPerPeriodMonthlyNormalized,idealAverageSpendingPerPeriodMonthlyNormalized);
        yAxisNumericLabel.setAxisStyle(axisStyle);
        
        // Adding axis info to chart.
        chart.addXAxisLabels(xAxisExplainLabel);
        chart.addXAxisLabels(xAxisNumericLabel);
        chart.addYAxisLabels(yAxisExplainLabel);
        chart.addYAxisLabels(yAxisNumericLabel);
        // Defining background and chart fills.
        chart.setBackgroundFill(Fills.newSolidFill(Color.newColor("1F1D1D")));
        LinearGradientFill fill = Fills.newLinearGradientFill(0, Color.newColor("363433"), 100);
        fill.addColorAndOffset(Color.newColor("2E2B2A"), 0);
        chart.setAreaFill(fill);
        String url = chart.toURLString();
        JLabel holder = lblHouseholdUsageImage;
        if(holder.isVisible())
        {
	        try {
				displayUrlString(url,holder);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				/*JOptionPane.showMessageDialog(this, 
											"Problem updating graph",
											"Error",
											JOptionPane.ERROR_MESSAGE);*/
				e.printStackTrace();
			}
        }
    }
}